package cn.edu.xmut.chen.zhlg.zhlg.vacancy.controller;

import cn.edu.xmut.chen.zhlg.common.HttpResult.Result;
import cn.edu.xmut.chen.zhlg.zhlg.user.entity.Resume;
import cn.edu.xmut.chen.zhlg.zhlg.user.service.ResumeService;
import cn.edu.xmut.chen.zhlg.zhlg.vacancy.entity.Apply;
import cn.edu.xmut.chen.zhlg.zhlg.vacancy.service.ApplyService;
import cn.edu.xmut.chen.zhlg.zhlg.vacancy.result.ApplyResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/apply")
public class ApplyController {
    @Autowired
    private ApplyService applyService;

    @Autowired
    private ResumeService resumeService;

    @PostMapping("")
    public Result apply(@RequestBody Apply apply) {
        apply.setStatus("待审核");
        apply.setApplyTime(new java.util.Date());
        return Result.success("申请成功").data(applyService.save(apply));
    }

    @GetMapping("/list")
    public Result list(
            @RequestParam String userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status) {

        Page<ApplyResult> page = new Page<>(pageNum, pageSize);
        return Result.success("获取成功").data(applyService.pageWithSql(page, userId, status));
    }

    @GetMapping("/listByUser")
    public Result listByUser(
            @RequestParam String userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status) {

        Page<ApplyResult> page = new Page<>(pageNum, pageSize);
        return Result.success("获取成功").data(applyService.applyListByUser(page, userId, status));
    }

    @GetMapping("/company/list")
    public Result companyList(
            @RequestParam String posterId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status) {
        // 使用SQL关联查询，通过job_id关联tb_vacancy表，然后通过poster_id过滤
        String sql = "SELECT a.*, v.vacancy_name, v.salary, r.name as user_name, r.phone as user_phone " +
                    "FROM tb_apply a " +
                    "LEFT JOIN tb_vacancy v ON a.job_id = v.id " +
                    "LEFT JOIN tb_resume r ON a.resume_id = r.id " +
                    "WHERE v.poster_id = ? ";
        
        if (status != null && !status.isEmpty()) {
            sql += "AND a.status = ? ";
        }
        
        sql += "ORDER BY a.apply_time DESC";
        
        // 执行分页查询
        Page<ApplyResult> page = new Page<>(pageNum, pageSize);
        return Result.success("获取成功").data(applyService.pageWithSql(page, posterId, status));
    }

    @PostMapping("/review")
    public Result review(@RequestBody Apply apply) {
        Apply existingApply = applyService.getById(apply.getId());
        if (existingApply != null) {
            existingApply.setStatus(apply.getStatus());
            existingApply.setReviewTime(new java.util.Date());
            existingApply.setRejectReason(apply.getRejectReason());
            return Result.success("审核成功").data(applyService.updateById(existingApply));
        }
        return Result.error("审核失败");
    }

    @GetMapping("/check")
    public Result checkApplied(@RequestParam String userId, @RequestParam String jobId) {
        LambdaQueryWrapper<Apply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Apply::getUserId, userId)
               .eq(Apply::getJobId, jobId);
        return Result.success("查询成功").data(applyService.count(wrapper) >= 1);
    }

    @GetMapping("/confirmResume")
    public Result confirmResume(@RequestParam String userId) {
        LambdaQueryWrapper<Resume> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Resume::getUserId, userId);
        return Result.success("查询成功").data(resumeService.count(wrapper) > 0);
    }

    @GetMapping("/count")
    public Result getApplyCount(@RequestParam String jobId) {
        LambdaQueryWrapper<Apply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Apply::getJobId, jobId);
        return Result.success("查询成功").data(applyService.count(wrapper));
    }
} 